<?php
/**
 * Created by PhpStorm.
 * User: rubekid
 * Date: 2016/10/29
 * Time: 12:34
 */

namespace SmartWiki\Http\Controllers;

use Faker\Provider\Uuid;
use Illuminate\Filesystem\Filesystem;
use League\Flysystem\Exception;
use PclZip;
use SmartWiki\Models\Dictionary;
use SmartWiki\Models\Project;


class DictionaryController extends Controller
{


    /**
     * 数据结构编辑首页
     * @param $project_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index($project_id)
    {
        if(empty($project_id) or $project_id <= 0){
            abort(404);
        }
        $project = Project::find($project_id);
        if(empty($project)){
            abort(404);
        }
        //判断是否有编辑权限
        if(Project::hasProjectEdit($project_id,$this->member->member_id) === false){
            abort(403);
        }

        $jsonArray = Dictionary::getDictionaries($project_id);
        $this->data['project_id'] = $project_id;
        $this->data['project'] = $project;
        $this->data['lists'] = $jsonArray;
        $this->data['member_projects'] = true;
        $this->data['is_owner'] = Project::isOwner($project_id,$this->member->member_id) ;

        return view('dictionary.dictionary',$this->data);
    }

    /**
     * 文件上传
     * @return \Illuminate\Http\JsonResponse
     */
    public function save()
    {
        $id = $this->request->input("id");
        $projectId = $this->request->input("project_id");
        $name = $this->request->input("name");
        $dbHost = $this->request->input("db_host");
        $dbUser = $this->request->input("db_user");
        $dbPasswd = $this->request->input("db_passwd");
        $dbName = $this->request->input("db_name");
        $isNew = empty($id);
        if(!$isNew) {
            //查看是否有重名数据结构
            $item = Dictionary::where('project_id', '=', $projectId)->where('name', '=', $name)->where('id','<>',$id)->first(['id']);

            if (empty($item) === false) {
                return $this->jsonResult(80005);
            }
        }else{
            //查看是否有重名数据结构
            $item = Dictionary::where('project_id', '=', $projectId)->where('name', '=', $name)->first(['id']);
            if (empty($item) === false) {
                return $this->jsonResult(80005);
            }
        }

        $dictionary = new Dictionary();

        if(!$isNew){
            $dictionary = Dictionary::find($id);
            if($dictionary == null){
                $data['success'] = 0;
                $data['message'] = '操作的数据结构不存在或已删除';
                return $this->response->json($data);
            }
            if(!empty($dbPasswd)){
                $dictionary->db_passwd = $dbPasswd;
            }
        }
        else{
            $dictionary->create_time = date('Y-m-d H:i:s');
            $dictionary->create_at = $this->member_id;
            $dictionary->db_passwd = $dbPasswd;
        }

        $dictionary->modify_time = date('Y-m-d H:i:s');
        $dictionary->modify_at = $this->member_id;
        $dictionary->project_id = $projectId;
        $dictionary->name = $name;
        $dictionary->db_host = $dbHost;
        $dictionary->db_user = $dbUser;
        $dictionary->db_name = $dbName;


        $dictionary->addOrUpdate();

        $data['success'] = 1;
        $data['message'] = 'ok';

        //消息通知
        $project = Project::find($projectId);
        if(!empty($project) && !empty($project->webhook)){
            $title = "数据结构变更通知";
            $desc = $this->member->nickname . ($isNew ? "新增数据结构":"更新了数据结构") . "《" .$dictionary->name . "》";
            $link = route('home.dictionary',['project_id' => $projectId, 'id' => $id]);
            $msgtype = "link";
            $picUrl = $this->member->headimgurl;
            if(strpos($picUrl, "/") == 0){
                $picUrl = url($picUrl);
            }
            //dtalk_notify($project->webhook, $title, $desc, $link, $msgtype, $picUrl);
        }
        return $this->response->json($data);
    }

    /**
     * 删除数据结构
     * @param int $axure_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {
        $dictionary = Dictionary::find($id);
        //如果数据结构不存在
        if(empty($dictionary)){
            return $this->jsonResult(70001);
        }
        //判断是否有编辑权限
        if(Project::hasProjectEdit($dictionary->project_id, $this->member_id) == false){
            return $this->jsonResult(70006);
        }
        try{

            Dictionary::deleteDictionary($id);
            return $this->jsonResult(0);
        }catch (\Exception $ex){
            if($ex->getCode() == 500){
                Log::error($ex->getMessage(),['trace'=>$ex->getTrace(),'file'=>$ex->getFile(),'line'=>$ex->getLine()]);
                return $this->jsonResult(500,null,'删除失败');
            }else{
                return $this->jsonResult($ex->getCode());
            }
        }
    }


}